package com.qujia.station.service.impl;

import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.DateUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.station.domain.NonClassSettlement;
import com.qujia.station.domain.Station;
import com.qujia.station.domain.dto.ClassPayTypeDto;
import com.qujia.station.domain.dto.QueryClassDto;
import com.qujia.station.domain.vo.QueryClassVo;
import com.qujia.station.mapper.NonClassSettlementMapper;
import com.qujia.station.service.IStationService;
import com.qujia.station.service.NonClassSettlementService;
import com.qujia.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service("nonClassSettlementService")
@Slf4j
public class NonClassSettlementServiceImpl implements NonClassSettlementService {

    @Autowired
    private NonClassSettlementMapper nonClassSettlementMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IStationService stationService;


    @Override
    public NonClassSettlement selectNonClassSettlementLastEndTime(NonClassSettlement nonClassSettlement) {
        if(Objects.isNull(nonClassSettlement.getStationId())){
            throw new CustomException("查询班结最后结束时间失败");
        }
        return nonClassSettlementMapper.selectNonClassSettlementLastEndTime(nonClassSettlement);
    }

    @Override
    public QueryClassVo initiateClassSe(NonClassSettlement nonClassSettlement) {
        NonClassSettlement classLastEndTime = new NonClassSettlement();
        classLastEndTime.setStationId(nonClassSettlement.getStationId());
        NonClassSettlement lastEndTime = selectNonClassSettlementLastEndTime(classLastEndTime);
        // 开始班结时间
        String beginTime = null;
        if(Objects.nonNull(lastEndTime)){
            beginTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,lastEndTime.getClassEndTime());
        }
        // 结束班结时间
        String endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date());

        QueryClassDto queryClass = new QueryClassDto();
        queryClass.setStationId(nonClassSettlement.getStationId());
        queryClass.setBeginTime(beginTime);
        queryClass.setEndTime(endTime);

        // 分组查询数据
        List<NonClassSettlement> classSettlementList = nonClassSettlementMapper.selectNonClassSettlementGroupOrder(queryClass);
        List<NonClassSettlement> nonClassCommoditylist = nonClassSettlementMapper.selectNonClassSettlementGroupOrderDetails(queryClass);
        if(CollectionUtils.isEmpty(classSettlementList)){
            return null;
        }
        classSettlementList.addAll(nonClassCommoditylist);
        // 详情数据组装
        QueryClassVo queryClassVo = getDetails(classSettlementList);
        queryClassVo.setBeginTime(beginTime);
        queryClassVo.setEndTime(endTime);

        return queryClassVo;
    }

    private QueryClassVo getDetails(List<NonClassSettlement> classSettlementList){

        BigDecimal payableAmount = BigDecimal.ZERO; // 应收合计
        BigDecimal actuallyAmount = BigDecimal.ZERO;  // 实收合计
        BigDecimal discountAmount = BigDecimal.ZERO;  // 优惠立减合计
        BigDecimal discountCouponAmount = BigDecimal.ZERO;  // 优惠券优惠合计
        BigDecimal totalDiscountAmount = BigDecimal.ZERO;  // 优惠合计
        BigDecimal refundAmount = BigDecimal.ZERO; // 退款

        List<Long> categoryIds = new ArrayList<>();
        List<NonClassSettlement> commodityClassList = new ArrayList<>(); // 销售商品汇总

        List<String> paytypeList = new ArrayList<>();
        List<ClassPayTypeDto> classPayTypeDtoList = new ArrayList<>(); // 支付汇总

        // 组装数据 返回
        for(NonClassSettlement classSettlement : classSettlementList){
            SysUser sysUser = sysUserService.selectUserById(Long.valueOf(classSettlement.getStaffId()));
            classSettlement.setStaffName(sysUser.getUserName());
            payableAmount = payableAmount.add(Objects.nonNull(classSettlement.getPayableAmount()) ? classSettlement.getPayableAmount() : BigDecimal.ZERO);
            actuallyAmount = actuallyAmount.add(Objects.nonNull(classSettlement.getActuallyAmount()) ? classSettlement.getActuallyAmount() : BigDecimal.ZERO);
            discountAmount = discountAmount.add(Objects.nonNull(classSettlement.getDiscountAmount()) ? classSettlement.getDiscountAmount() : BigDecimal.ZERO);
            discountCouponAmount = discountCouponAmount.add(Objects.nonNull(classSettlement.getDiscountCouponAmount()) ? classSettlement.getDiscountCouponAmount() : BigDecimal.ZERO);
            refundAmount = refundAmount.add(Objects.nonNull(classSettlement.getRefundAmount()) ? classSettlement.getRefundAmount() : BigDecimal.ZERO);

            // 商品汇总 数据组装
            if(categoryIds.contains(classSettlement.getCategoryId())){
                for (NonClassSettlement settlement : commodityClassList) {
                    if(settlement.getCategoryId().equals(classSettlement.getCategoryId())){
                        settlement.setCommodityNum(settlement.getCommodityNum() + classSettlement.getCommodityNum());
                        settlement.setTotalPrice((Objects.nonNull(settlement.getTotalPrice()) ? settlement.getTotalPrice() : BigDecimal.ZERO).add(Objects.nonNull(classSettlement.getTotalPrice()) ? classSettlement.getTotalPrice() : BigDecimal.ZERO));
                    }
                }
            }else if(Objects.nonNull(classSettlement.getCategoryId())){
                categoryIds.add(classSettlement.getCategoryId());
                commodityClassList.add(classSettlement);
            }

            // 支付方式汇总 组装
            if(paytypeList.contains(classSettlement.getPayType())){
                for (ClassPayTypeDto classPayTypeDto : classPayTypeDtoList) {
                    if(classPayTypeDto.getPayType().equals(classSettlement.getPayType())){
                        classPayTypeDto.setActuallyAmount((Objects.nonNull(classPayTypeDto.getActuallyAmount()) ? classPayTypeDto.getActuallyAmount() : BigDecimal.ZERO).add(Objects.nonNull(classSettlement.getActuallyAmount()) ? classSettlement.getActuallyAmount() : BigDecimal.ZERO));
                        classPayTypeDto.setRefundAmount((Objects.nonNull(classPayTypeDto.getRefundAmount()) ? classPayTypeDto.getRefundAmount() : BigDecimal.ZERO).add(Objects.nonNull(classSettlement.getRefundAmount()) ? classSettlement.getRefundAmount() : BigDecimal.ZERO));
                    }
                }
            }else if(StringUtils.isNotBlank(classSettlement.getPayType())){
                paytypeList.add(classSettlement.getPayType());
                ClassPayTypeDto classPayTypeDto = new ClassPayTypeDto();
                classPayTypeDto.setPayType(classSettlement.getPayType());
                classPayTypeDto.setActuallyAmount(Objects.nonNull(classSettlement.getActuallyAmount()) ? classSettlement.getActuallyAmount() : BigDecimal.ZERO);
                classPayTypeDto.setRefundAmount(Objects.nonNull(classSettlement.getRefundAmount()) ? classSettlement.getRefundAmount() : BigDecimal.ZERO);
                classPayTypeDtoList.add(classPayTypeDto);
            }
        }

        // 销售商品汇总 合计
        NonClassSettlement totalNonClassSettlement = new NonClassSettlement();
        totalNonClassSettlement.setCategoryName("合计");
        Long num = 0l; // 合计销售数量
        BigDecimal commodityPayableAmount = BigDecimal.ZERO; // 合计总计

        if(CollectionUtils.isNotEmpty(commodityClassList)) {
            for (NonClassSettlement classSettlement : commodityClassList) {
                num = num + classSettlement.getCommodityNum();
                commodityPayableAmount = commodityPayableAmount.add(Objects.nonNull(classSettlement.getTotalPrice()) ? classSettlement.getTotalPrice() : BigDecimal.ZERO);
            }
            totalNonClassSettlement.setCommodityNum(num);
            totalNonClassSettlement.setTotalPrice(commodityPayableAmount);
            commodityClassList.add(totalNonClassSettlement);
        }

        // 支付方式汇总 合计
        ClassPayTypeDto totalClassPayTypeDto = new ClassPayTypeDto();
        totalClassPayTypeDto.setPayType("合计");
        BigDecimal payTypeActuallyAmount = BigDecimal.ZERO; // 合计收款合计
        BigDecimal payTypeRefundAmount = BigDecimal.ZERO; // 合计收款合计

        if(CollectionUtils.isNotEmpty(classPayTypeDtoList)){
            for (NonClassSettlement classSettlement : classSettlementList) {
                payTypeActuallyAmount = payTypeActuallyAmount.add(Objects.nonNull(classSettlement.getActuallyAmount()) ? classSettlement.getActuallyAmount() : BigDecimal.ZERO);
                payTypeRefundAmount = payTypeRefundAmount.add(Objects.nonNull(classSettlement.getRefundAmount()) ? classSettlement.getRefundAmount() : BigDecimal.ZERO);
            }
            totalClassPayTypeDto.setActuallyAmount(payTypeActuallyAmount);
            totalClassPayTypeDto.setRefundAmount(payTypeRefundAmount);
            classPayTypeDtoList.add(totalClassPayTypeDto);
        }


        // 预班结 数据组装
        totalDiscountAmount = discountAmount.add(discountCouponAmount);
        QueryClassVo queryClassVo = new QueryClassVo();
        queryClassVo.setPayableAmount(payableAmount);
        queryClassVo.setActuallyAmount(actuallyAmount);
        queryClassVo.setTotalDiscountAmount(totalDiscountAmount);
        queryClassVo.setRefundAmount(refundAmount);
        queryClassVo.setCommodityClassList(commodityClassList);
        queryClassVo.setClassPayTypeDtoList(classPayTypeDtoList);

        return queryClassVo;
    }

    @Override
    public List<NonClassSettlement> selectNonClassSettlementList(NonClassSettlement nonClassSettlement) {
        List<NonClassSettlement> classSettlementList = nonClassSettlementMapper.selectNonClassSettlementList(nonClassSettlement);
        for (NonClassSettlement classSettlement : classSettlementList) {
            Station station = stationService.selectStationById(classSettlement.getStationId());
            classSettlement.setStationName(station.getStationName());
        }
        return classSettlementList;
    }

    @Override
    public QueryClassVo selectNonClassSettlementDetails(String classNo) {
        List<NonClassSettlement> classSettlementList = nonClassSettlementMapper.selectNonClassSettlementDetails(classNo);
        if(CollectionUtils.isEmpty(classSettlementList)){
            return null;
        }
        QueryClassVo queryClassVo = getDetails(classSettlementList);
        NonClassSettlement classOne = classSettlementList.get(0);
        queryClassVo.setClassNo(classOne.getClassNo());
        queryClassVo.setStationId(classOne.getStationId());
        queryClassVo.setStationName(classOne.getStationName());
        queryClassVo.setCreateName(classOne.getCreateName());
        queryClassVo.setClassStartTime(classOne.getClassStartTime());
        queryClassVo.setClassEndTime(classOne.getClassEndTime());

        return queryClassVo;
    }
}
